<template>
  <t-space direction="vertical" align="center" style="width: 100%">
    <t-form :data="form" @submit="submitForm" class="card-form">
      <t-form-item label="年级" name="grade">
        <t-radio-group v-model="form.grade">
          <t-radio-button v-for="grade in config.grade" :value="grade">
            {{ grade }}
          </t-radio-button>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="学科" name="subject">
        <t-radio-group v-model="form.subject">
          <t-radio-button v-for="subject in config.subjects" :value="subject">
            {{ subject }}
          </t-radio-button>
        </t-radio-group>
      </t-form-item>
      <t-form-item label="班级" name="class_names">
        <t-collapse>
          <t-collapse-panel header="选择班级">
            <t-space direction="vertical">
              <t-checkbox-group v-model="form.class_names">
                <t-checkbox v-for="class_name in config.class_names" :value="class_name">
                  {{ class_name }}
                </t-checkbox>
              </t-checkbox-group>
            </t-space></t-collapse-panel></t-collapse>
      </t-form-item>
      <div>已选择配置的卡片数量：{{ lengthOfSelectedConfig }}</div>
      <t-form-item label="问题" name="question">
        <t-textarea placeholder="请输入问题" autofocus v-model="form.question" id="question-input"
          :autosize="{ minRows: 5 }" />
      </t-form-item>
      <t-form-item label="答案" name="answer">
        <t-textarea placeholder="请输入答案" v-model="form.answer" :autosize="{ minRows: 5 }" />
      </t-form-item>
      <t-button block theme="primary" variant="base" type="submit">确定(Ctrl+Enter)</t-button>
    </t-form></t-space>
</template>

<script setup>
import { MessagePlugin } from "tdesign-vue-next";
import { ref, onMounted, onUnmounted, watch } from "vue";
import axios from "axios";

// 从本地存储加载配置（只加载grade,subject,class_names）
const loadConfigFromStorage = () => {
  const savedConfig = localStorage.getItem("addCardConfig");
  if (savedConfig) {
    const {
      grade = "",
      subject = "",
      class_names = [],
    } = JSON.parse(savedConfig);
    return { grade, subject, class_names };
  }
  return { grade: "", subject: "", class_names: [] };
};

// 保存配置到本地存储（只保存grade,subject,class_names）
const saveConfigToStorage = (config) => {
  const { grade, subject, class_names } = config;
  localStorage.setItem(
    "addCardConfig",
    JSON.stringify({ grade, subject, class_names })
  );
};

const config = ref({
  grade: [],
  subjects: [],
  class_names: [],
});
const lengthOfSelectedConfig = ref(0);

const form = ref({
  ...loadConfigFromStorage(), // 只初始化配置相关字段
  question: "",
  answer: "",
});

// 获取配置数据
const loadConfig = async () => {
  try {
    const response = await axios.get("/api/config");
    config.value = response.data;
    console.log("配置加载成功:", config.value);
  } catch (error) {
    MessagePlugin.error("获取配置失败，请截图并发送给作者", error);
  }
};

// 提交表单
const submitForm = async () => {
  if (!validateForm()) return;

  try {
    const payload = {
      grade: form.value.grade,
      subject: form.value.subject,
      class_names: form.value.class_names,
      cards: [
        {
          question: form.value.question,
          answer: form.value.answer,
        },
      ],
    };

    const response = await axios.post("/api/add_cards", payload);
    MessagePlugin.success(`成功添加${response.data.added}张卡片`);
    // 只清空问题和答案字段
    form.value.question = "";
    form.value.answer = "";
    // 保存当前配置
    saveConfigToStorage(form.value);
  } catch (error) {
    MessagePlugin.error(
      "提交失败: " + error.response?.data?.error || error.message
    );
  }
};

// 获取选中配置的卡片数量
const fetchCardCountByConfig = async (configData) => {
  try {
    const response = await axios.get("/api/list_cards", {
      params: {
        grade: configData.grade,
        subject: configData.subject,
        class_name: configData.class_names,
      },
    });
    lengthOfSelectedConfig.value = response.data.cards.length;
  } catch (error) {
    console.error("获取卡片数量失败:", error);
    lengthOfSelectedConfig.value = 0;
  }
};

// 修改watch监听，只监听配置相关字段的变化
watch(
  () => ({
    grade: form.value.grade,
    subject: form.value.subject,
    class_names: form.value.class_names,
  }),
  async (newConfig) => {
    saveConfigToStorage(newConfig); // 保存配置到本地存储
    // 聚焦问题输入框
    setTimeout(() => {
      const container = document.getElementById("question-input");
      if (container) {
        const textarea = container.querySelector("textarea");
        if (textarea) {
          textarea.focus();
        }
      }
    }, 5);
    // 获取选中配置的卡片数量
    await fetchCardCountByConfig(newConfig);
  },
  { deep: true }
);

onMounted(async () => {
  await loadConfig();
  document.title = "添加卡片";
  window.addEventListener("keydown", handleSubMitKey);

  // 页面加载后，获取初始配置下的卡片数量
  const initialConfig = {
    grade: form.value.grade,
    subject: form.value.subject,
    class_names: form.value.class_names,
  };
  if (initialConfig.grade && initialConfig.subject && initialConfig.class_names.length > 0) {
    await fetchCardCountByConfig(initialConfig);
  }
});
onUnmounted(() => {
  window.removeEventListener("keydown", handleSubMitKey);
});
// 表单验证
const validateForm = () => {
  if (!form.value.grade) {
    MessagePlugin.warning("请选择年级");
    return false;
  }
  if (!form.value.subject) {
    MessagePlugin.warning("请选择学科");
    return false;
  }
  if (form.value.class_names.length === 0) {
    MessagePlugin.warning("请至少选择一个班级");
    return false;
  }
  if (!form.value.question.trim()) {
    MessagePlugin.warning("请输入问题内容");
    return false;
  }
  return true;
};

// 添加watch监听表单变化
watch(
  form,
  (newVal) => {
    saveConfigToStorage(newVal);
  },
  { deep: true }
);

const handleSubMitKey = (event) => {
  if (event.ctrlKey && event.key === "Enter") {
    // 阻止默认行为
    event.preventDefault();
    // 触发按钮点击事件
    submitForm();
  }
};
</script>

<style scoped>
.card-form {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>